<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
    String path=request.getContextPath();
%>
<style type="text/css">

    /*设置 layui 表格中单元格内容溢出可见样式*/
    #divtable .layui-table-view,
    #divtable .layui-table-box,
    #divtable .layui-table-body{overflow: visible;}
    #divtable .layui-table-cell{height: auto; overflow: visible;}

    /*文本对齐方式*/
    .text-center{text-align: center;}
    /* 使得下拉框与单元格刚好合适 */
    td .layui-form-select{
        margin-top: -5px;
        margin-left: -15px;
        margin-right: -15px;
    }
    #divtable .layui-anim-upbit{
        margin-top: -10px;
    }
</style>
<div id="yclTransferOrder" style="margin: 30px">
    <%--query tools--%>
    <blockquote class="layui-elem-quote">
        <form class="layui-form">
            <div class="layui-fluid">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">调拨单号</label>
                            <div class="layui-input-inline">
                                <input type="text" id="tranCode" maxlength="20" class="layui-input"
                                       v-model="queryParams.tranCode"/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">物料名称</label>
                            <div class="layui-input-inline">
                                <input type="text" maxlength="20" class="layui-input" v-model="queryParams.materialName"/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">创建日期</label>
                            <div class="layui-input-inline">
                                <input type="text" id="createTimeTrans" class="layui-input"
                                       v-model="queryParams.createTime"/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">调出厂区</label>
                            <div class="layui-form layui-input-inline" lay-filter="fromTransAreaCode">
                                <select id="fromTransAreaCode" lay-filter="fromTransAreaCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in transArealist" :value="item.id" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">调出仓库</label>
                            <div class="layui-form layui-input-inline" lay-filter="fromTransStoreCode">
                                <select id="fromTransStoreCode" lay-filter="fromTransStoreCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in storelist" :value="item.code" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal"
                                    @click="queryPageView">
                                <i class="layui-icon">&#xe615;</i>查询
                            </button>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm"
                                    @click="restQueryParams">
                                <i class="layui-icon">&#xe669;</i>重置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </blockquote>
    <div class="layui-btn-container" style="margin-bottom: 0px;padding-bottom: 0px;">
        <button type="button" @click="addTransferOrder" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe654;</i>新建
        </button>
        <%--        <button type="button" @click="edtTransferOrder" class="layui-btn layui-btn-sm layui-btn-normal">--%>
        <%--            <i class="layui-icon">&#xe642;</i>编辑--%>
        <%--        </button>--%>
        <button type="button" @click="delTransferOrder" class="layui-btn layui-btn-sm layui-btn-warm">
            <i class="layui-icon">&#xe65c;</i>撤回
        </button>
        <button type="button" @click="printTransferOrderOut" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe66d;</i>出库单
        </button>
        <button type="button" @click="printTransferOrderIn" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe66d;</i>入库单
        </button>
        <button type="button" @click="printFactoryOut" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe66d;</i>出厂单
        </button>
    </div>
    <%-- table grid --%>
    <table id="tableGridTransferOrder" lay-filter="tableGridTransferOrder"></table>
    <%-- table grid toolbar --%>

    <div class="layui-btn-container" style="margin-bottom: 0px;padding-bottom: 0px;">
        <label style="width: 65px">上架详情</label>
        <button id="btnTransferAdd" type="button" @click="addTransferOrderUp" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe654;</i>增行
        </button>
        <button id="btnTransferDel" type="button" @click="delTransferOrderUp" class="layui-btn layui-btn-sm layui-btn-danger">
            <i class="layui-icon">&#xe640;</i>删除
        </button>
        <button id="btnTransferSave" type="button" @click="saveTransferOrderUp" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe605;</i>提交
        </button>
    </div>
    <%-- table grid --%>
        <div id="divtable">
    <table id="tableGridTransferOrderUp"></table>
        </div>
    <%-- table grid toolbar --%>
    <iframe style="visibility:hidden;" id="myiframe" name="myiframe" src="<%=path%>/ycl/insidewarehouse/transferOrder/toPrint" width=0 height=0> </iframe>
</div>
<script src="/wms/plugins/public_components/js/jquery-2.1.4.js"></script>
<script src="/wms/static/js/techbloom/LodopFuncs.js" charset="utf-8"></script>
<script>
    const context_path = '${APP_PATH}';
    const tableTransferOrder = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate;

    var tableTransIns;
    var LODOP; //声明为全局变量
    //获取table的list集合
    let vm = new Vue({
        el: '#yclTransferOrder',
        data: {
            selectedRow:null,
            transArealist:[],
            storelist:[],
            shelfCodelist:[],
            upDownList:[],
            queryParams: {
                tranCode: "",
                createTime: "",
                materialName: "",
                fromAreaCode: "",
                fromStoreCode: ""
            }
        },
        methods: {
            addTransferOrder(){
                layer.open({
                    title: '新增'
                    , type: 2
                    , area: ['1200px', '600px'] //宽高
                    , maxmin: true
                    , content: context_path + '/ycl/insidewarehouse/transferOrder/toEdit'
                });
            },
            edtTransferOrder(){
                var selectData = layui.table.checkStatus('tableGridTransferOrder').data;
                if (selectData.length!=1)
                {
                    layer.alert('请选择一条记录!');
                    return false;
                }
                if (selectData[0].status!=null&&selectData[0].status!='0')
                {
                    layer.alert('该记录已经开始，不能编辑!');
                    return false;
                }
                layer.open({
                    title: '新增'
                    , type: 2
                    , area: ['1000px', '400px'] //宽高
                    , maxmin: true
                    , content: context_path + '/ycl/insidewarehouse/TransferOrder/toEdit?id='+selectData[0].id
                });
            },
            printTransferOrderOut(){
                var selectData = layui.table.checkStatus('tableGridTransferOrder').data;
                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                var frm =document.getElementById('myiframe');
                frm.src='/wms/ycl/insidewarehouse/transferOrder/toPrint?tcode='+selectData[0].tranCode;
                $(frm).load(function(){
                    LODOP=getLodop();
                    var strHtml=frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0,0,"100%","100%",strHtml);
                    LODOP.PREVIEW();
                });
            },
            printTransferOrderIn(){
                var selectData = layui.table.checkStatus('tableGridTransferOrder').data;
                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                var frm =document.getElementById('myiframe');
                frm.src='/wms/ycl/insidewarehouse/transferOrder/toPrintIn?tcode='+selectData[0].tranCode;
                $(frm).load(function(){
                    LODOP=getLodop();
                    var strHtml=frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0,0,"100%","100%",strHtml);
                    LODOP.PREVIEW();
                });
            },
            printFactoryOut(){
                var selectData = layui.table.checkStatus('tableGridTransferOrder').data;
                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                $.ajax({
                    type: 'POST',
                    url: "/wms/ycl/insidewarehouse/transferOrder/selectTransferOrderEntity",
                    async: false,
                    data: {
                        id:selectData[0].id
                    },
                    success: res=> {
                        if (res != null) {
                            let obj = {
                                line: []
                            };
                            obj.goodType = '自有' //物料类型
                            obj.billType = '移位调拨'   //单据类型
                            obj.driver = ''   //驾驶员号码
                            obj.autoNum = ''   //车牌号
                            obj.company = ''   //公司
                            obj.transport = ''   //运输方
                            obj.sendout = ''   //发出单位
                            obj.receiver = ''   //接收单位
                            obj.sendNum = ''   //派车单号
                            obj.applyUser = res.creator   //申请人
                            obj.applyTel = ''   //申请人号码
                            obj.applyDate = res.createTime   //申请日期
                            obj.remark = ''   //备注
                            obj.orderCode = res.tranCode  //导入来源
                            res.line.forEach(m=>{
                                const line = {};
                                line.materialCode = m.materialCode  //物料编码
                                line.materialName = m.materialName  //物料名称
                                line.unit = m.primaryUnit  //单位
                                line.quality = m.outQuantity  //数量
                                line.orderCode = res.tranCode  //导入来源
                                line.comments = ''  //备注
                                obj.line.push(line)
                            })
                            layer.open({
                                title: '打印'
                                ,type: 2
                                ,area: ['1200px', '600px'] //宽高
                                ,maxmin: true
                                ,content: context_path + '/ycl/purchasein/factory/printView?obj=' + encodeURI(JSON.stringify(obj))
                            });
                        }
                    }
                })
            },
            delTransferOrder(){
                var selectData = layui.table.checkStatus('tableGridTransferOrder').data;
                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                if (selectData[0].lineState == '1')
                {
                    layer.alert('完成状态无法撤回!');
                    return;
                }
                layer.confirm('确认撤回？', function(){
                    $.get(context_path + '/ycl/insidewarehouse/transferOrder/deleteByLineIds', {
                        lineIds: selectData[0].lineId
                    }, function (res) {
                        tableTransferOrder.reload('tableGridTransferOrder', {
                            where: vm.queryParams
                        });
                        layer.msg('操作成功！');
                    })
                });
            },
            addTransferOrderUp(){
                var selectData = tableTransferOrder.checkStatus('tableGridTransferOrderUp').data;
                if (selectData.length == 0)
                {
                    layer.alert('请先选中一条记录!');
                    return;
                }
                var oldData = tableTransferOrder.cache['tableGridTransferOrderUp'];
                let newData = [];
                oldData.forEach(m=>{
                    newData.push(m);
                    if(m.tempId === selectData[0].tempId){
                        var newRow = {};
                        newRow.tempId = new Date().valueOf();
                        newRow.lineId = m.lineId;
                        newRow.businessCode = m.businessCode;
                        newRow.areaCode = m.areaCode;
                        newRow.storeCode = m.storeCode;
                        newRow.fromLocator = m.fromLocator;
                        newRow.quantity = m.quantity;
                        newRow.primaryUnit = m.primaryUnit;
                        newRow.materialCode = m.materialCode;
                        newRow.materialName = m.materialName;
                        newRow.lotsNum = m.lotsNum;
                        newRow.state = '1';
                        newRow.inoutType = '1';
                        newData.push(newRow);
                    }
                })
                tableTransIns.reload({
                    data : newData
                });
            },
            delTransferOrderUp(){
                let selectData = tableTransferOrder.checkStatus('tableGridTransferOrderUp').data;
                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                layer.confirm('确认删除？', function(){
                    if (selectData[0].id != undefined && selectData[0].id != '') {
                        $.get(context_path + '/ycl/operation/yclInOutFlow/delete', {
                            ids: selectData[0].id
                        }, function (res) {
                        })
                    }
                    let oldData = tableTransferOrder.cache['tableGridTransferOrderUp'];
                    for(let i = 0; i < oldData.length; i++){
                        if(oldData[i].tempId === selectData[0].tempId){
                            oldData.splice(i,1);
                        }
                    }
                    tableTransIns.reload({
                        data: oldData
                    });
                    layer.msg('操作成功！');
                });
            },
            saveTransferOrderUp(){
                this.upDownList = tableTransferOrder.cache['tableGridTransferOrderUp']
                if (this.upDownList.length == 0)
                {
                    layer.alert('暂无上架数据!');
                    return;
                }
                var updownQuantityError = false;
                var locatorError = false;
                this.upDownList.forEach(m=>{
                    if (m.updownQuantity==null||m.updownQuantity==''||isNaN(m.updownQuantity))
                    {
                        updownQuantityError=true;
                    }
                    if (m.locatorCode==null ||m.locatorCode=='')
                    {
                        locatorError=true;
                    }
                })
                if (locatorError)
                {
                    layer.alert('上架库位不能为空!');
                    return;
                }
                if (updownQuantityError)
                {
                    layer.alert('移出数量为空或非数字!');
                    return;
                }
                let tempData = [];
                this.upDownList.forEach(m=>{
                    let tmp = tempData.find(x=>x.lineId==m.lineId);
                    if (tmp!=undefined){
                        tmp.updownQuantity=Number(tmp.updownQuantity)+Number(m.updownQuantity)
                    }else{
                        let newRow = {}
                        newRow.lineId=m.lineId
                        newRow.quantity=m.quantity
                        newRow.updownQuantity=m.updownQuantity
                        tempData.push(newRow)
                    }
                })
                if (tempData.some(m=> m.quantity!=m.updownQuantity))
                {
                    layer.alert('上架数量须等于调拨数量!');
                    return;
                }
                console.log(this.selectedRow)
                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/insidewarehouse/transferOrder/saveBatch/"+this.selectedRow.tranType,
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(this.upDownList),
                    success: res=> {
                        if (res.result) {
                            this.reloadUp();
                            this.queryPageView();
                        }
                        layer.msg(res.msg);
                    }
                })
            },
            reloadUp(){
                $.get(context_path + '/ycl/operation/yclInOutFlow/listView', {
                    businessCode:this.selectedRow.tranCode
                }, function (res) {
                    let dbRes = res.data;
                    if (dbRes.length >0)
                    {
                        $('#btnTransferAdd').addClass('layui-btn-disabled');
                        $('#btnTransferAdd').attr('disabled', 'disabled');
                        $('#btnTransferDel').addClass('layui-btn-disabled');
                        $('#btnTransferDel').attr('disabled', 'disabled');
                        $('#btnTransferSave').addClass('layui-btn-disabled');
                        $('#btnTransferSave').attr('disabled', 'disabled');
                        tableTransIns.reload({
                            data : dbRes
                        });
                    }else{
                        $('#btnTransferAdd').removeClass('layui-btn-disabled');
                        $('#btnTransferAdd').removeAttr('disabled', 'disabled');
                        $('#btnTransferDel').removeClass('layui-btn-disabled');
                        $('#btnTransferDel').removeAttr('disabled', 'disabled');
                        $('#btnTransferSave').removeClass('layui-btn-disabled');
                        $('#btnTransferSave').removeAttr('disabled', 'disabled');
                        //请求
                        $.get(context_path + '/ycl/insidewarehouse/transferOrder/list?tranCode='+vm.selectedRow.tranCode, {
                        }, function (re) {
                            var tid = new Date().valueOf();
                            re.data.forEach(r=>{
                                while(tid === new Date().valueOf())
                                {
                                    continue;
                                }
                                tid = new Date().valueOf();
                                var newRow = {};
                                newRow.tempId = tid;
                                newRow.lineId = r.lineId;
                                newRow.businessCode = r.tranCode;
                                newRow.areaCode = r.fromAreaCode;
                                newRow.storeCode = r.toStoreCode;
                                newRow.fromLocator = r.fromLocator;
                                newRow.quantity = r.outQuantity;
                                newRow.primaryUnit = r.primaryUnit;
                                newRow.materialCode = r.materialCode;
                                newRow.materialName = r.materialName;
                                newRow.lotsNum = r.lotsNum;
                                newRow.state = '1';
                                newRow.inoutType = '1';
                                dbRes.push(newRow);
                            })
                            tableTransIns.reload({
                                data : dbRes
                            });
                        })
                    }
                })
            },
            inittableTransIns() {
                tableTransferOrder.render({
                    elem: '#tableGridTransferOrder'
                    , url: context_path + '/ycl/insidewarehouse/transferOrder/list'
                    , page: true
                    , limit:5
                    , id: "tableGridTransferOrder"
                    , size: 'sm'
                    , defaultToolbar: []
                    , cols: [[
                        {type: 'radio'}
                        , {field: 'id', hide: true}
                        , {field: 'lineId', hide: true}
                        , {field: 'tranCode', title: '调拨单号',width:'160'}
                        , {field: 'materialCode', title: '物料编码',width:'150'}
                        , {field: 'materialName', title: '物料名称',width:'200'}
                        , {field: 'outQuantity', title: '数量',width:'80'}
                        , {field: 'lotsNum', title: '批次号',width:'100'}
                        , {field: 'fromArea', title: '调出厂区',width:'120'}
                        , {field: 'fromStore', title: '调出仓库',width:'150'}
                        , {field: 'fromLocator', title: '调出库位',width:'100'}
                        , {field: 'toStore', title: '调入仓库',width:'150'}
                        , {field: 'createTime', title: '创建时间',width:'100'}
                        // , {field: 'status', title: '状态',width:'80', templet: (d)=>d.lineState == '1'?'完成':''}
                    ]]
                });

                tableTransIns = tableTransferOrder.render({
                    elem: '#tableGridTransferOrderUp'
                    ,data:[]
                    ,limit:999
                    ,size: 'sm'
                    ,cols: [[
                        {type: 'radio'}
                        ,{field: 'tempId', hide: true}
                        ,{field: 'materialCode', title: '物料编码'}
                        ,{field: 'lotsNum', title: '批次号'}
                        ,{field: 'quantity', title: '调拨数量'}
                        ,{field: 'primaryUnit', title: '单位'}
                        ,{field: 'locatorCode', title: '上架库位', templet: (d)=>vm.renderSelectOptions(d)}
                        ,{field: 'updownQuantity', title: '上架数量', style:'background-color: #5fb878;color:#fff', edit: 'text'}
                        ,{field: 'materialName', title: '物料名称'}
                    ]]
                });
            },
            queryPageView() {
                vm.queryParams.fromAreaCode = $('#fromTransAreaCode').val();
                vm.queryParams.fromStoreCode = $('#fromTransStoreCode').val();
                console.log(vm.queryParams)
                tableTransferOrder.reload('tableGridTransferOrder', {
                    page: {curr:1},
                    where: vm.queryParams
                });
            },
            restQueryParams() {
                vm.queryParams = {
                    tranCode: "",
                    createTime: "",
                    materialName: "",
                    fromAreaCode: "",
                    fromStoreCode: ""
                }
                $('#fromTransAreaCode').val("");
                $('#fromTransStoreCode').val("");
                form.render('select','fromTransAreaCode');
                form.render('select','fromTransStoreCode');
                tableTransferOrder.reload('tableGridTransferOrder', {
                    page: {curr:1},
                    where: vm.queryParams
                });
            },
            renderSelectOptions(e){
                let html = [];
                html.push('<div class="layui-form" lay-filter="shelfCode">');
                html.push('<select name="shelfCode" id="shelfCode" data-value="'+e.tempId+'" lay-filter="shelfCode" lay-search="">');
                html.push('<option value="">请选择</option>');
                this.shelfCodelist.forEach(m=>{
                    html.push('<option value="');
                    html.push(m.code);
                    html.push('"');
                    if(m.code == e.locatorCode ){
                        html.push(' selected="selected"');
                    }
                    html.push('>');
                    html.push(m.codename);
                    html.push('</option>');
                })
                html.push('</select></div>');
                return html.join('');
            }
        },
        created() {
            $.get(context_path + '/ycl/baseinfo/basedata/area/0'
                , res=> {
                    this.transArealist = res.data;
                    console.log(this.transArealist)
                    this.$nextTick(() => {
                        form.render('select','fromTransAreaCode');
                    });
                })
        },
        mounted() {
            form.render();
            laydate.render({
                elem: '#createTimeTrans'
                ,range: true
                ,done: function (value, date, endDate) {
                    vm.queryParams.createTime = value
                }
            });

            this.inittableTransIns()
        }
    })

    tableTransferOrder.on('row(tableGridTransferOrder)', function(obj){
        vm.selectedRow = obj.data;
        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        $.get(context_path + '/goods/getShelfByFactWareCode.do', {
            warehouseCode : vm.selectedRow.toStoreCode,
            entityId: vm.selectedRow.toAreaCode,
            queryString: '',
            pageSize: 999,
            pageNo: 1
        }, function (res) {
            vm.shelfCodelist = res.result
            vm.reloadUp();
        })
    });

    //监听select
    form.on('select(fromTransAreaCode)', function (data) {
        $.get(context_path + '/ycl/baseinfo/basedata/store/'+data.value
            , res=> {
                vm.storelist = res.data;
                vm.$nextTick(() => {
                    form.render('select','fromTransStoreCode');
                })
            })
    });

    function tableRender(){
        tableTransferOrder.reload('tableGridTransferOrder', {
            page: {curr:1},
            where: vm.queryParams
        });
    }
    //监听select
    form.on('select(shelfCode)', function (data) {
        var elem = data.othis.parents('tr');
        var id = elem.first().find('td').eq(1).text();
        let val = data.value
        this.tbData = tableTransferOrder.cache['tableGridTransferOrderUp'];
        this.tbData.forEach(n=>{
            if (n.tempId==id)
            {
                n.locatorCode = data.value;
            }
        })
        tableTransIns.reload({
            data : this.tbData
        });
    });
</script>